package testPaperJBFX;

import android.app.Activity;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.text.Html;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.example.hyznbk.R;
import com.example.hyznbk.utils.DensityUtils;
import com.example.hyznbk.view.base.BaseActivity;
import com.example.hyznbk.view.widget.QuesIndexView;

import lancooControl.Control;
import lancooCustomListview.BounceScrollView;

import static lancooUpLoad.PaperInfor.isfirstSubmit;
import static testPaperJBFX.BasicReviewPaperActivity.InforBasicReview;
import static testPaperJBFX.BasicReviewPaperActivity.VpBasicReviewPaper;


/**
 * Created by Administrator on 2017/3/14.
 * modify by tmlong on 2017/10/16
 */
public class BasicReviewAnswerSheet extends PopupWindow {

    private View mMenuView;
    private RelativeLayout RLayoutBackMenu;
//    private TextView TvClose;
    private TextView TvTitle;
    private LinearLayout LayoutAssess;
    private TextView TvAllScore;
    private TextView TvUseTime;
    private Button BtnCheckAllAnalysis;//查看全部解析

    private BounceScrollView mScrollView;


    private Activity mContext;


    private final RelativeLayout[] rLayoutQuesList;

    //,int currentI,int currentJ

    private int mCurPageIndex;
    private int mCurQuesIndex;
    private final TextView[] tvTypeName;

    public BasicReviewAnswerSheet(final Activity context,int curPageIndex,int curQuesIndex) {
        super(context);
        this.mCurPageIndex = curPageIndex;
        this.mCurQuesIndex = curQuesIndex;
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        mMenuView = inflater.inflate(R.layout.answer_sheet, null);

        //核心代码.
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            context.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }

        mContext = context;

        RLayoutBackMenu = (RelativeLayout) mMenuView.findViewById(R.id.rlayout_back_menu);
        //关闭按钮
//        TvClose = (TextView) mMenuView.findViewById(R.id.tv_close);

        mScrollView = (BounceScrollView) mMenuView.findViewById(R.id.scroll_ques_index);

        RelativeLayout relToolbar = (RelativeLayout) mMenuView.findViewById(R.id.rlayout_back);
        int statusBarHeight = ((BaseActivity) context).getStatusBarHeight();
        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) relToolbar.getLayoutParams();
        layoutParams.setMargins(0,statusBarHeight,0,0);

        RLayoutBackMenu.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                //销毁弹出框
                dismiss();
                if (BtnCheckAllAnalysis.getVisibility() == View.VISIBLE){
                    mContext.finish();
                }
            }
        });

//        TvClose.setOnClickListener(new OnClickListener() {
//
//            public void onClick(View v) {
//                //销毁弹出框
//                dismiss();
//                if (BtnCheckAllAnalysis.getVisibility() == View.VISIBLE){
//                    mContext.finish();
//                }
//            }
//        });
        //答题卡标题文字
        TvTitle = (TextView) mMenuView.findViewById(R.id.tv_tittle);
        //联系报告自评内容
        LayoutAssess = (LinearLayout) mMenuView.findViewById(R.id.layout_assess);
        //总得分
        TvAllScore = (TextView) mMenuView.findViewById(R.id.tv_all_score);
        //用时
        TvUseTime = (TextView) mMenuView.findViewById(R.id.tv_use_time);
        //查看全部解析
        BtnCheckAllAnalysis = (Button) mMenuView.findViewById(R.id.btn_check_all_analysis);


        //设置SelectPicPopupWindow的View
        this.setContentView(mMenuView);
        //设置SelectPicPopupWindow弹出窗体的宽
        this.setWidth(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体的高
        this.setHeight(LayoutParams.FILL_PARENT);
        //设置SelectPicPopupWindow弹出窗体可点击
        this.setFocusable(true);
        //设置SelectPicPopupWindow弹出窗体动画效果
        this.setAnimationStyle(R.style.Popupwindow);
        //实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        //设置SelectPicPopupWindow弹出窗体的背景
        this.setBackgroundDrawable(dw);

        LinearLayout LayoutAnswerSheet = (LinearLayout) mMenuView.findViewById(R.id.layout_answer_sheet);
        int sumPaperCount = InforBasicReview.getPaperContent().size();
        Double stuScore = 0.0;
        Double allScore = 0.0;


        tvTypeName = new TextView[sumPaperCount];
        rLayoutQuesList = new RelativeLayout[sumPaperCount];
        for(int i=0;i<sumPaperCount;i++){
            String strTypeName = InforBasicReview.getPaperContent().get(i).getTypeName();
            tvTypeName[i] = new TextView(mContext);
//            TvTypeName[i].setText("第"+String.valueOf(i+1)+"大题   "+strTypeName);
            tvTypeName[i].setText(Html.fromHtml("<font color='#cccccc'><middle><middle>"+"第"+String.valueOf(i+1)+"大题"+"</middle></middle></font>"+
                    "<font color='#000000'><middle><middle>"+"&nbsp;&nbsp;&nbsp;"+strTypeName+"</middle></middle></font>"));
            tvTypeName[i].setPadding(DensityUtils.dp2px(mContext,15), DensityUtils.dp2px(mContext,15),0,DensityUtils.dp2px(mContext,15));
            //tvTypeName[i].setPadding(10,0,0,0);
            LayoutAnswerSheet.addView(tvTypeName[i]);
            rLayoutQuesList[i] = new RelativeLayout(mContext);
            //rLayoutQuesList[i].setPadding(0,10,0,20);

            int sumTotalItemCount = InforBasicReview.getPaperContent().get(i).getTotalItemCount();
            DisplayMetrics dm = new DisplayMetrics();
            context.getWindowManager().getDefaultDisplay().getMetrics(dm);
            int width = dm.widthPixels;
            int height = dm.heightPixels;

            final QuesIndexView[] quesIndexViews = new QuesIndexView[sumTotalItemCount];
            //Button[] BtnQuesNumber = new Button[sumTotalItemCount];
            int k = -1;

            int sumOfQuesKong = 0;//单道大题的总空数
            for(int p=0;p<sumTotalItemCount;p++){
                sumOfQuesKong = sumOfQuesKong+Control.backSum(InforBasicReview.getPaperContent().get(i).getQueList().get(p).getAnswer(),"$、")+1;
            }

            for(int j = 0;j<sumTotalItemCount;j++){
                quesIndexViews[j] = new QuesIndexView(mContext);
                quesIndexViews[j].setTag(j);
                if ( i == mCurPageIndex && j == mCurQuesIndex){
                    quesIndexViews[j].setQuesIndexChecked(true);
                    mScrollView.post(new Runnable() {
                        @Override
                        public void run() {
                           // int[] location = new int[2];
                            int top1 = tvTypeName[mCurPageIndex].getTop();
                            top1 -= 10;
                           // int top = (rLayoutQuesList[mCurPageIndex].findViewWithTag(mCurQuesIndex)).getTop();
                            if (top1 < 0){
                                top1 = 0;
                            }
                            mScrollView.scrollTo(0,top1);
                        }
                    });

                }

                if(InforBasicReview.getState()==2) {
                    //已提交
                    if (!GetStuAssessTrue(i, j).equals("")) {
                        Log.e("===YYGetStuAssess==","==222=="+strTypeName);
                        Log.e("===YYGetStuAssess==","==333=="+"===iii=="+i+"===jjj=="+j);
                        Log.e("===YYGetStuAssess==","==000=="+GetStuAssess(i, j));
                        Log.e("===YYGetStuAssess==","==111=="+GetStuAssessTrue(i, j));
                        //自评不为空
                        int sumOfRight = Control.backSum(GetStuAssessTrue(i, j),"正确")+Control.backSum(GetStuAssessTrue(i, j),"优秀")+Control.backSum(GetStuAssessTrue(i, j),"一般");
                        int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
//                        if(sumOfRight>0) {
                            if (Control.getCorrectRate(Float.valueOf(sumOfRight), Float.valueOf(sumOfQuestion)) < 0.7) {
                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
                            } else {
                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
                            }
//                        }else{
//                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
//                        }

                    } else {
                        //自评为空
                        Log.e("===XXGetStuAnswer==","==222=="+strTypeName);
                        Log.e("===XXGetStuAnswer==","==333=="+"===iii=="+i+"===jjj=="+j);
                        Log.e("===XXGetStuAnswer==","==000=="+GetStuAnswer(i, j));
                        Log.e("===XXGetStuAnswer==","==111=="+GetStuAnswerTrue(i, j));
                        if (GetStuAnswerTrue(i, j).equals("")) {//学生答案为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
                        } else {
                            //学生答案不为空
                            int sumOfRight = 0;
                            int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
                            for(int m=0;m<sumOfQuestion;m++){
                                String strQuestionStuAnswer = Control.returnArray(GetStuAnswer(i, j),"$、",2)[m];
                                String strQuestionAnswer = Control.returnArray(GetAnswer(i, j),"$、",2)[m];
                                int sumOfQuestionAnswer = Control.backSum(strQuestionAnswer,"$/")+1;
                                for(int p=0;p<sumOfQuestionAnswer;p++){
                                    if(strQuestionStuAnswer.trim().equals(Control.returnArray(strQuestionAnswer,"$/",2)[p])){
                                        sumOfRight++;
                                        break;
                                    }
                                }
                            }
//                            if(sumOfRight>0) {
                                if (Control.getCorrectRate(Float.valueOf(sumOfRight), Float.valueOf(sumOfQuestion)) < 0.7) {
                                    quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_WRONG);
                                } else {
                                    quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_RIGHT);
                                }
//                            }else{
//                                quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
//                            }
                        }

                    }
                }else{
                    //未作答或未提交
                    if (!GetStuAssessTrue(i, j).equals("")) {//自评不为空
                        quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
                    } else {//自评为空
                        Log.e("===GetStuAnswer==","===="+GetStuAnswer(i, j));
                        if (GetStuAnswerTrue(i, j).equals("")) {//学生答案为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_NO_ANSWER);
                        } else {//学生答案不为空
                            quesIndexViews[j].setQuesIndexStatus(QuesIndexView.STATUS_ANSWER);
                        }

                    }
                }


                quesIndexViews[j].setQuesIndexText(String.valueOf(j + 1));
                final int finalI = i;
                final int finalJ = j;
                quesIndexViews[j].setQuesIndexClickListener(new QuesIndexView.QuesIndexClickListener() {
                    @Override
                    public void onClick(View v) {
                       /* if (preClickIndexId != -1){
                            ((QuesIndexView)rLayoutQuesList[preGroupClickIndexId].findViewWithTag(preClickIndexId)).setQuesIndexChecked();
                        }*/
                        Log.e("=====finalJ========","===aaaaaa===="+finalJ);
                        VpBasicReviewPaper.setCurrentItem(finalI);
                       /* preGroupClickIndexId = finalI;
                        preClickIndexId = finalJ;*/
//                            VpAnswer.setCurrentItem(finalJ);

                        Fragment fragment = (Fragment) ((BasicReviewPaperFragmentAdapter) VpBasicReviewPaper.getAdapter()).instantiateItem(VpBasicReviewPaper, finalI);
                        ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
                        childViewPage.setCurrentItem(finalJ);

                        dismiss();
                    }
                });

                /*BtnQuesNumber[j].setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Log.e("=====finalJ========","===aaaaaa===="+finalJ);
                            VpBasicReviewPaper.setCurrentItem(finalI);
//                            VpAnswer.setCurrentItem(finalJ);

                            Fragment fragment = (Fragment) ((BasicReviewPaperFragmentAdapter) VpBasicReviewPaper.getAdapter()).instantiateItem(VpBasicReviewPaper, finalI);
                            ViewPager childViewPage = (ViewPager) fragment.getView().findViewById(R.id.viewpage_answer);
                            childViewPage.setCurrentItem(finalJ);

                            dismiss();
                        }
                    });*/
                    RelativeLayout.LayoutParams btnParams = new RelativeLayout.LayoutParams(width / 9, width / 9);

                    if (j % 6 == 0) {
                        k++;
                    }

                    btnParams.leftMargin = ((width) / 6) * (j % 6) + (width / 6 - width / 9) / 2;   //横坐标定位
                    btnParams.topMargin = 20 + (width / 9 + 20) * k;   //纵坐标定位


                if(InforBasicReview.getState()==2){

                    if(strTypeName.equals("看图写句子")||strTypeName.equals("句子填空")|| strTypeName.equals("翻译填空")||
                            strTypeName.equals("听力填空")||strTypeName.equals("阅读填空")|| strTypeName.equals("短文填空")||
                            strTypeName.equals("词汇填空")){

//                        String stuAssessOfQuestion = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();

                        int sumOfQuestion = Control.backSum(GetAnswer(i,j),"$、")+1;
                        for(int c=0;c<sumOfQuestion;c++){
                            Log.e("====cccccc=====",c+"====GetStuAnswer===="+GetStuAnswer(i,j));
                            String smallQuesStuAnswer = Control.returnArray(GetStuAnswer(i,j),"$、",2)[c];
                            String smallQuesAnswer = Control.returnArray(GetAnswer(i,j),"$、",2)[c];
                            String smallQuesStuAssess = Control.returnArray(GetStuAssess(i,j),"$、",2)[c];
                            if(smallQuesStuAssess.equals("正确")){
                                stuScore = stuScore + InforBasicReview.getPaperContent().get(i).getScore()/sumOfQuesKong;
                            }else if(smallQuesStuAssess.equals("")){
                                for (int b = 0; b < Control.backSum(smallQuesAnswer, "$/") + 1; b++) {
                                    if (smallQuesStuAnswer.equals(Control.returnArray(smallQuesAnswer, "$/", 2)[b])) {
                                        stuScore = stuScore + InforBasicReview.getPaperContent().get(i).getScore() / sumOfQuesKong;
                                        break;
                                    }
                                }
                            }
                        }


                    }else if(strTypeName.equals("作文")||strTypeName.equals("翻译题")){
                        if(GetStuAssess(i,j).equals("优秀")||GetStuAssess(i,j).equals("一般")||GetStuAssess(i,j).equals("")){
                            stuScore = stuScore + InforBasicReview.getPaperContent().get(i).getScore() / sumOfQuesKong;
                        }
                    }else if(strTypeName.equals("阅读简答")){

                        if(GetStuAssess(i,j).equals("优秀")||GetStuAssess(i,j).equals("一般")||GetStuAssess(i,j).equals("")){
                            stuScore = stuScore + InforBasicReview.getPaperContent().get(i).getScore() / sumOfQuesKong;
                        }
                    }else{
                        if(InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer().
                                equals(InforBasicReview.getPaperContent().get(i).getQueList().get(j).getAnswer())){
                            stuScore = stuScore+InforBasicReview.getPaperContent().get(i).getScore()/sumTotalItemCount;
                        }
                    }

                }

                rLayoutQuesList[i].addView(quesIndexViews[j],btnParams);
            }

            allScore = allScore+InforBasicReview.getPaperContent().get(i).getScore();
            LayoutAnswerSheet.addView(rLayoutQuesList[i]);

            Log.e("====AAAtypename=====",strTypeName+"====stuScore===="+stuScore);

        }

        /*********************************************/
        /*********************************************/
        if(InforBasicReview.getState()!=2){
            TvTitle.setText("答题卡");
            LayoutAssess.setVisibility(View.GONE);
            BtnCheckAllAnalysis.setVisibility(View.GONE);
        }else{
            TvTitle.setText("练习报告");
            LayoutAssess.setVisibility(View.GONE);

            stuScore = Double.valueOf(new java.text.DecimalFormat("#0.0").format(stuScore));

            TvAllScore.setText(stuScore+"分/"+allScore+"分");
            int useTime = InforBasicReview.getDuration();
            int hour = useTime/3600;
            int minute = useTime/60%60;
            int second = useTime%60;
            String useTimeLong = "";
            if(hour>0){
                useTimeLong = hour+"时"+minute+"分"+second+"秒";
            }else{
                if(minute>0){
                    useTimeLong = minute+"分"+second+"秒";
                }else{
                    useTimeLong = second+"秒";
                }
            }
            TvUseTime.setText(useTimeLong);
            Log.e("===BRSheet====","====isfirstSubmit==="+isfirstSubmit);
            if(isfirstSubmit) {
                BtnCheckAllAnalysis.setVisibility(View.VISIBLE);
            }else{
                BtnCheckAllAnalysis.setVisibility(View.GONE);

            }
            BtnCheckAllAnalysis.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
//                    checkAllAnalysisListener.onClick();
                    dismiss();
//                    VpBasicReviewPaper.setCurrentItem(0);
                }
            });
        }
        /*********************************************/
        /*********************************************/

    }

    /*
    * 获取学生答案
    * */
    private String GetStuAnswer(int i,int j){
//        String strStuAnswer = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
//        strStuAnswer = strStuAnswer.replaceAll("\\$、","");
//        if(!strStuAnswer.equals("")){
//            strStuAnswer = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
//        }
        return InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
    }

    /*
    * 用于答题卡题号颜色判断
    * */
    private String GetStuAnswerTrue(int i,int j){
        String strStuAnswer = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
        strStuAnswer = strStuAnswer.replaceAll("\\$、","");
        if(!strStuAnswer.equals("")){
            strStuAnswer = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAnswer();
        }
        return strStuAnswer;
    }

    /*
    * 获取参考答案
    * */
    private String GetAnswer(int i,int j){
        return InforBasicReview.getPaperContent().get(i).getQueList().get(j).getAnswer();
    }

    /*
    * 获取自评或及机评结果
    * */
    private String GetStuAssess(int i,int j){
//        String strStuAssess = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();
//        strStuAssess = strStuAssess.replaceAll("$、","");
//        if(!strStuAssess.equals("")){
//            strStuAssess = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();
//        }
        return InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();
    }

    /*
    * 用于答题卡题号颜色判断
    * */
    private String GetStuAssessTrue(int i,int j){
        String strStuAssess = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();
        strStuAssess = strStuAssess.replaceAll("\\$、","");
        if(!strStuAssess.equals("")){
            strStuAssess = InforBasicReview.getPaperContent().get(i).getQueList().get(j).getStuAssess();
        }
        return strStuAssess;
    }


    /***********************************************************************/
    /*
    * 查看全部解析
    * */
    /***********************************************************************/
//    public interface CheckAllAnalysisListener{
//        void onClick();
//    }
//
//    private CheckAllAnalysisListener checkAllAnalysisListener;
//
//    public void setCheckAllAnalysis(CheckAllAnalysisListener listener){
//        this.checkAllAnalysisListener = listener;
//    }
    /***********************************************************************/
    /***********************************************************************/
}